<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>Kotlin -- Object关键字 | 码行</title><meta name="author" content="Carl Su"><meta name="copyright" content="Carl Su"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="语义：  匿名内部类 单例模式 伴生对象  本质： 在定义一个类的同时还创建了对象 匿名内部类在Java中，我们一般这么写 public interface OnClickListener &amp;#123;        void onClick(View v);    &amp;#125;image.setOnClickListener(new View.OnClickListener() &amp;#123;">
<meta property="og:type" content="article">
<meta property="og:title" content="Kotlin -- Object关键字">
<meta property="og:url" content="https://devsu.top/posts/c4e3d35a/index.html">
<meta property="og:site_name" content="码行">
<meta property="og:description" content="语义：  匿名内部类 单例模式 伴生对象  本质： 在定义一个类的同时还创建了对象 匿名内部类在Java中，我们一般这么写 public interface OnClickListener &amp;#123;        void onClick(View v);    &amp;#125;image.setOnClickListener(new View.OnClickListener() &amp;#123;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img2.baidu.com/it/u=2005100522,649410059&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500">
<meta property="article:published_time" content="2022-08-19T06:44:26.000Z">
<meta property="article:modified_time" content="2023-03-15T07:57:08.179Z">
<meta property="article:author" content="Carl Su">
<meta property="article:tag" content="Kotlin">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img2.baidu.com/it/u=2005100522,649410059&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500"><link rel="shortcut icon" href="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"><link rel="canonical" href="https://devsu.top/posts/c4e3d35a/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?6243425e2ecb037931274c4ca1db3132";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":300},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Carl Su","link":"链接: ","source":"来源: 码行","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Kotlin -- Object关键字',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-15 15:57:08'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://s2.loli.net/2023/03/09/QrI9mgJ4XlbEPzN.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">169</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">37</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">38</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg fixed" id="page-header" style="background-image: url('https://img2.baidu.com/it/u=2005100522,649410059&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500')"><nav id="nav"><span id="blog-info"><a href="/" title="码行"><img class="site-icon" src="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"/><span class="site-name">码行</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Kotlin -- Object关键字</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-08-19T06:44:26.000Z" title="发表于 2022-08-19 14:44:26">2022-08-19</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-15T07:57:08.179Z" title="更新于 2023-03-15 15:57:08">2023-03-15</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/">Android</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/Kotlin/">Kotlin</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/Kotlin/Foundation/">Foundation</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>15分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Kotlin -- Object关键字"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>语义：</p>
<ul>
<li>匿名内部类</li>
<li>单例模式</li>
<li>伴生对象</li>
</ul>
<p><em><strong>本质： 在定义一个类的同时还创建了对象</strong></em></p>
<h3 id="匿名内部类"><a href="#匿名内部类" class="headerlink" title="匿名内部类"></a>匿名内部类</h3><p>在Java中，我们一般这么写</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">OnClickListener</span> &#123;</span><br><span class="line">        <span class="keyword">void</span> <span class="title function_">onClick</span><span class="params">(View v)</span>;</span><br><span class="line">    &#125;</span><br><span class="line">image.setOnClickListener(<span class="keyword">new</span> <span class="title class_">View</span>.OnClickListener() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onClick</span><span class="params">(View v)</span> &#123;</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br></pre></td></tr></table></figure>

<p>在Kotlin中</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line">binding.textView.setOnClickListener(<span class="keyword">object</span> : View.OnClickListener&#123;</span><br><span class="line">            <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onClick</span><span class="params">(v: <span class="type">View</span>?)</span></span> &#123;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br></pre></td></tr></table></figure>

<p>.</p>
<p>不过，在 Kotlin 中，匿名内部类还有一个特殊之处，就是我们在使用 object 定义匿名内部类的时候，其实还可以<strong>在继承一个抽象类的同时，来实现多个接口。</strong></p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title class_">A</span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">funA</span><span class="params">()</span></span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">B</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">funB</span><span class="params">()</span></span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">C</span> &#123;</span><br><span class="line">    <span class="keyword">abstract</span> <span class="function"><span class="keyword">fun</span> <span class="title">findC</span><span class="params">()</span></span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">object</span> : C(),A,B&#123;</span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">funA</span><span class="params">()</span></span> &#123;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">funB</span><span class="params">()</span></span> &#123;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">findC</span><span class="params">()</span></span> &#123;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h3 id="单例模式"><a href="#单例模式" class="headerlink" title="单例模式"></a>单例模式</h3><figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">object</span> AppManager &#123;</span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">login</span><span class="params">()</span></span> &#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>反编译后的Java代码</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">AppManager</span> &#123;</span><br><span class="line">   <span class="meta">@NotNull</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> AppManager INSTANCE;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">login</span><span class="params">()</span> &#123;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">private</span> <span class="title function_">AppManager</span><span class="params">()</span> &#123;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">static</span> &#123;</span><br><span class="line">      <span class="type">AppManager</span> <span class="variable">var0</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">AppManager</span>();</span><br><span class="line">      INSTANCE = var0;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，当我们使用 object 关键字定义单例类的时候，Kotlin 编译器会将其<strong>转换成静态代码块的单例模式</strong>。因为static{}代码块当中的代码(在类初始化的时候完成加载)，由虚拟机保证它只会被执行一次，因此，它在保证了线程安全的前提下，同时也保证我们的 INSTANCE 只会被初始化一次。</p>
<p>缺点:</p>
<ul>
<li>不支持懒加载</li>
<li>不支持传参构造单例</li>
</ul>
<h3 id="object-伴生对象"><a href="#object-伴生对象" class="headerlink" title="object: 伴生对象"></a>object: 伴生对象</h3><p>我们都知道，Kotlin 当中没有 static 关键字，所以我们没有办法直接定义静态方法和静态变量。不过，Kotlin 还是为我们提供了伴生对象，来帮助实现静态方法和变量。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span> &#123;</span><br><span class="line">    <span class="keyword">object</span> InnerSingleton &#123;</span><br><span class="line">        <span class="function"><span class="keyword">fun</span> <span class="title">foo</span><span class="params">()</span></span> &#123;&#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，我们可以将单例定义到一个类的内部。这样，单例就跟外部类形成了一种嵌套的关系，而我们要使用它的话，可以直接这样写：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line">Person.InnerSingleton.foo()</span><br></pre></td></tr></table></figure>

<p>以上的代码看起来，foo() 就像是静态方法一样。不过，为了一探究竟，我们可以看看 Person 类反编译成 Java 后是怎样的。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">Person</span> &#123;</span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">InnerSingleton</span> &#123;</span><br><span class="line">      <span class="meta">@NotNull</span></span><br><span class="line">      <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> InnerSingleton INSTANCE;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">foo</span><span class="params">()</span> &#123;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">private</span> <span class="title function_">InnerSingleton</span><span class="params">()</span> &#123;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">static</span> &#123;</span><br><span class="line">         <span class="type">InnerSingleton</span> <span class="variable">var0</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">InnerSingleton</span>();</span><br><span class="line">         INSTANCE = var0;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，foo() 并不是静态方法，它实际上是通过调用单例 InnerSingleton 的实例上的方法实现的：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// Kotlin当中这样调用</span></span><br><span class="line">Person.InnerSingleton.foo()</span><br><span class="line"><span class="comment">//      等价</span></span><br><span class="line"><span class="comment">//       ↓  java 当中这样调用</span></span><br><span class="line">Person.InnerSingleton.INSTANCE.foo()</span><br></pre></td></tr></table></figure>

<p>这时候，你可能就会想：<strong>要如何才能实现类似 Java 静态方法的代码呢？</strong></p>
<p>其实很简单，我们可以使用“@JvmStatic”这个注解，如以下代码所示：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span> &#123;</span><br><span class="line">    <span class="keyword">object</span> InnerSingleton &#123;</span><br><span class="line">        <span class="meta">@JvmStatic</span></span><br><span class="line">        <span class="function"><span class="keyword">fun</span> <span class="title">foo</span><span class="params">()</span></span> &#123;&#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>反编译后的Java代码</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">Person</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">InnerSingleton</span> &#123;</span><br><span class="line">        <span class="meta">@NotNull</span></span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> InnerSingleton INSTANCE;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@JvmStatic</span></span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">foo</span><span class="params">()</span> &#123;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> <span class="title function_">InnerSingleton</span><span class="params">()</span> &#123;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">static</span> &#123;</span><br><span class="line">            <span class="type">InnerSingleton</span> <span class="variable">var0</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">InnerSingleton</span>();</span><br><span class="line">            INSTANCE = var0;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以发现，foo() 这个方法就变成了 InnerSingleton 类当中的一个静态方法了。</p>
<p>这样一来，不管事Kotlin还是Java，调用方式都变成了</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line">Person.InnerSingleton.foo()</span><br></pre></td></tr></table></figure>

<p>看到这里，如果你足够细心，你一定会产生一个疑问：上面的静态内部类“InnerSingleton”看起来有点多余，我们平时在 Java 当中写的静态方法，不应该是只有一个层级吗？比如：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Person</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">foo</span><span class="params">()</span> &#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 调用的时候，只有一个层级</span></span><br><span class="line">Person.foo()</span><br></pre></td></tr></table></figure>

<p>答案当然是有的，我们只需要在前面例子当中的 object 关键字前面，加一个 <strong>companion 关键字</strong>即可。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span> &#123;</span><br><span class="line"><span class="comment">//  改动在这里</span></span><br><span class="line"><span class="comment">//     ↓</span></span><br><span class="line">    <span class="keyword">companion</span> <span class="keyword">object</span> InnerSingleton &#123;</span><br><span class="line">        <span class="meta">@JvmStatic</span></span><br><span class="line">        <span class="function"><span class="keyword">fun</span> <span class="title">foo</span><span class="params">()</span></span> &#123;&#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>companion object，在 Kotlin 当中就被称作伴生对象，它其实是我们嵌套单例的一种特殊情况。也就是，<strong>在伴生对象的内部，如果存在“@JvmStatic”修饰的方法或属性，它会被挪到伴生对象外部的类当中，变成静态成员。</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">Person</span> &#123;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> Person.<span class="type">InnerSingleton</span> <span class="variable">InnerSingleton</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Person</span>.InnerSingleton((DefaultConstructorMarker)<span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 注意这里</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">foo</span><span class="params">()</span> &#123;</span><br><span class="line">      InnerSingleton.foo();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">InnerSingleton</span> &#123;</span><br><span class="line">      <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">foo</span><span class="params">()</span> &#123;&#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">private</span> <span class="title function_">InnerSingleton</span><span class="params">()</span> &#123;&#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">public</span> <span class="title function_">InnerSingleton</span><span class="params">(DefaultConstructorMarker $constructor_marker)</span> &#123;</span><br><span class="line">         <span class="built_in">this</span>();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>  根据上面反编译后的代码，我们可以看出来，被挪到外部的静态方法 foo()，它最终还是调用了单例 InnerSingleton 的成员方法 foo()，所以它只是做了一层转接而已。</p>
<p>  到这里，也许你已经明白 object 单例、伴生对象中间的演变关系了：普通的 object 单例，演变出了嵌套的单例；嵌套的单例，演变出了伴生对象。</p>
<p>你也可以换个说法：<strong>嵌套单例，是 object 单例的一种特殊情况；伴生对象，是嵌套单例的一种特殊情况</strong>。</p>
<p>如果comanion中的方法，不加@JvmStatic修饰</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">Person</span> &#123;</span><br><span class="line">   <span class="meta">@NotNull</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">InnerSingleton</span> <span class="variable">InnerSingleton</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">InnerSingleton</span>((DefaultConstructorMarker)<span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">InnerSingleton</span> &#123;</span><br><span class="line">      <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">foo</span><span class="params">()</span> &#123;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">private</span> <span class="title function_">InnerSingleton</span><span class="params">()</span> &#123;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// $FF: synthetic method</span></span><br><span class="line">      <span class="keyword">public</span> <span class="title function_">InnerSingleton</span><span class="params">(DefaultConstructorMarker $constructor_marker)</span> &#123;</span><br><span class="line">         <span class="built_in">this</span>();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">PersonKt</span> &#123;</span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">()</span> &#123;</span><br><span class="line">       <span class="comment">//注意这里</span></span><br><span class="line">      Person.InnerSingleton.foo();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// $FF: synthetic method</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] var0)</span> &#123;</span><br><span class="line">      main();</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>调用方法:</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line">Person.foo()</span><br></pre></td></tr></table></figure>

<p><strong>对于companion中用@JvmStatic修饰的方法而言，加不加@JvmStatic都不影响我们的调用，如果不加@JvmStatic修饰，编译器会自动实现Person.InnerSingleton.foo()，区别只在于是否将方法移到伴生对象外部的类当中，变成静态成员</strong></p>
<h4 id="伴生对象的实战应用"><a href="#伴生对象的实战应用" class="headerlink" title="伴生对象的实战应用"></a>伴生对象的实战应用</h4><h5 id="工厂模式"><a href="#工厂模式" class="headerlink" title="工厂模式"></a>工厂模式</h5><p>所谓的工厂模式，就是指当我们想要统一管理一个类的创建时，我们可以将这个类的构造函数声明成 private，然后用工厂模式来暴露一个统一的方法，以供外部使用。Kotlin 的伴生对象非常符合这样的使用场景：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">//  私有的构造函数，外部无法调用</span></span><br><span class="line"><span class="comment">//            ↓</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">User</span> <span class="keyword">private</span> <span class="keyword">constructor</span>(name: String) &#123;</span><br><span class="line">    <span class="keyword">companion</span> <span class="keyword">object</span> &#123;</span><br><span class="line">        <span class="meta">@JvmStatic</span></span><br><span class="line">        <span class="function"><span class="keyword">fun</span> <span class="title">create</span><span class="params">(name: <span class="type">String</span>)</span></span>: User? &#123;</span><br><span class="line">            <span class="comment">// 统一检查，比如敏感词过滤</span></span><br><span class="line">            <span class="keyword">return</span> User(name)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​	在这个例子当中，我们将 User 的构造函数声明成了 private 的，这样，外部的类就无法直接使用它的构造函数来创建实例了。与此同时，我们通过伴生对象，暴露出了一个 create() 方法。在这个 create() 方法当中，我们可以做一些统一的判断，比如敏感词过滤、判断用户的名称是否合法。</p>
<p>​	另外，由于“伴生对象”本质上还是属于 User 的嵌套类，伴生对象仍然还算是在 User 类的内部，所以，我们是可以在 create() 方法内部调用 User 的构造函数的。</p>
<p>​	这样，我们就通过“伴生对象”巧妙地实现了工厂模式。接下来，我们继续看看如何使用“伴生对象”来实现更加复杂的单例设计模式。</p>
<h5 id="另外4中单例模式的写法"><a href="#另外4中单例模式的写法" class="headerlink" title="另外4中单例模式的写法"></a>另外4中单例模式的写法</h5><p>​	在前面，我们已经学习了 Kotlin 当中最简单的单例模式，也就是 object 关键字。同时，我们也提到了，这种方式虽然简洁，但它也存在两大问题：第一，无法懒加载；第二，不支持传参。</p>
<p>​	那么，Kotlin 当中有没有既支持懒加载又支持传参的单例模式呢？</p>
<p>​	答案当然是有的。接下来，我们就来了解下 Kotlin 里功能更加全面的 4 种单例模式，分别是懒加载委托单例模式、Double Check 单例模式、抽象类模板单例，以及接口单例模板</p>
<h6 id="第一种：懒加载委托"><a href="#第一种：懒加载委托" class="headerlink" title="第一种：懒加载委托"></a>第一种：懒加载委托</h6><p>​	其实，针对懒加载的问题，我们在原有的代码基础上做一个非常小的改动就能优化，也就是借助 Kotlin 提供的“委托”语法。</p>
<p>​	比如，针对前面的单例代码，我们在它内部的属性上使用 by lazy 将其包裹起来，这样我们的单例就能得到一部分的懒加载效果</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">object</span> UserManager &#123;</span><br><span class="line">    <span class="comment">// 对外暴露的 user</span></span><br><span class="line">    <span class="keyword">val</span> user <span class="keyword">by</span> lazy &#123; loadUser() &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">loadUser</span><span class="params">()</span></span>: User &#123;</span><br><span class="line">        <span class="comment">// 从网络或者数据库加载数据</span></span><br><span class="line">        <span class="keyword">return</span> User.create(<span class="string">&quot;tom&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">login</span><span class="params">()</span></span> &#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​	可以看到，UserManager 内部的 user 变量变成了懒加载，只要 user 变量没有被使用过，它就不会触发 loadUser() 的逻辑。</p>
<p>​	这其实是一种简洁与性能的折中方案。一个对象所占用的内存资源毕竟不大，绝大多数情况我们都可以接受。而从服务器去请求用户信息所消耗的资源更大，我们能够保证这个部分是懒加载的，就算是不错的结果了。</p>
<h6 id="第二种-伴生对象Double-Check"><a href="#第二种-伴生对象Double-Check" class="headerlink" title="第二种: 伴生对象Double Check"></a>第二种: 伴生对象Double Check</h6><figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">UserManager</span> <span class="keyword">private</span> <span class="keyword">constructor</span>(name: String) &#123;</span><br><span class="line">    <span class="keyword">companion</span> <span class="keyword">object</span> &#123;</span><br><span class="line">        <span class="meta">@Volatile</span> <span class="keyword">private</span> <span class="keyword">var</span> INSTANCE: UserManager? = <span class="literal">null</span></span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">fun</span> <span class="title">getInstance</span><span class="params">(name: <span class="type">String</span>)</span></span>: UserManager =</span><br><span class="line">            <span class="comment">// 第一次判空</span></span><br><span class="line">            INSTANCE?: synchronized(<span class="keyword">this</span>) &#123;</span><br><span class="line">            <span class="comment">// 第二次判空</span></span><br><span class="line">                INSTANCE?:UserManager(name).also &#123; INSTANCE = it &#125;</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用</span></span><br><span class="line">UserManager.getInstance(<span class="string">&quot;Tom&quot;</span>)</span><br></pre></td></tr></table></figure>

<p>​	这种写法，其实是借鉴于 GitHub 上的Google 官方 Demo，它本质上就是 Java 的 Double Check。</p>
<p>​	首先，我们定义了一个伴生对象，然后在它的内部，定义了一个 INSTANCE，它是 private 的，这样就保证了它无法直接被外部访问。同时它还被注解“@Volatile”修饰了，这可以保证 INSTANCE 的可见性，而 getInstance() 方法当中的 synchronized，保证了 INSTANCE 的原子性。因此，这种方案还是线程安全的。</p>
<p>​	同时，我们也能注意到，初始化情况下，INSTANCE 是等于 null 的。这也就意味着，只有在 getInstance() 方法被使用的情况下，我们才会真正去加载用户数据。这样，我们就实现了整个 UserManager 的懒加载，而不是它内部的某个参数的懒加载。</p>
<p>​	另外，由于我们可以在调用 getInstance(name) 方法的时候传入初始化参数，因此，这种方案也是支持传参的。</p>
<p>​	不过，以上的实现方式仍然存在一个问题，在实现了 UserManager 以后，假设我们又有一个新的需求，要实现 PersonManager 的单例，这时候我们就需要重新写一次 Double Check 的逻辑。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">UserManager</span> <span class="keyword">private</span> <span class="keyword">constructor</span>(name: String) &#123;</span><br><span class="line">    <span class="keyword">companion</span> <span class="keyword">object</span> &#123;</span><br><span class="line">    <span class="comment">// 省略代码</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">PersonManager</span> <span class="keyword">private</span> <span class="keyword">constructor</span>(name: String) &#123;</span><br><span class="line">    <span class="keyword">companion</span> <span class="keyword">object</span> &#123;</span><br><span class="line">        <span class="meta">@Volatile</span> <span class="keyword">private</span> <span class="keyword">var</span> INSTANCE: PersonManager? = <span class="literal">null</span></span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">fun</span> <span class="title">getInstance</span><span class="params">(name: <span class="type">String</span>)</span></span>: PersonManager =</span><br><span class="line">            INSTANCE?: synchronized(<span class="keyword">this</span>) &#123;</span><br><span class="line">                INSTANCE?:PersonManager(name).also &#123; INSTANCE = it &#125;</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​	可以看到，不同的单例当中，我们必须反复写 Double Check 的逻辑，这是典型的坏代码。这种方式不仅很容易出错，同时也不符合编程规则（Don’t Repeat Yourself）。</p>
<h6 id="第三种：-类抽象模板"><a href="#第三种：-类抽象模板" class="headerlink" title="第三种： 类抽象模板"></a>第三种： 类抽象模板</h6><p>​	我们来仔细分析下第二种写法的单例。其实很快就能发现，它主要由两个部分组成：第一部分是 INSTANCE 实例，第二部分是 getInstance() 函数。</p>
<p>​	现在，我们要尝试对这种模式进行抽象。在面向对象的编程当中，我们主要有两种抽象手段，第一种是<strong>类抽象模板</strong>，第二种是<strong>接口抽象模板</strong>。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">//  ①                          ②                      </span></span><br><span class="line"><span class="comment">//  ↓                           ↓                       </span></span><br><span class="line"><span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">BaseSingleton</span>&lt;<span class="type">in P, out T</span>&gt; &#123;</span><br><span class="line">    <span class="meta">@Volatile</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> instance: T? = <span class="literal">null</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//                       ③</span></span><br><span class="line">    <span class="comment">//                       ↓</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">abstract</span> <span class="function"><span class="keyword">fun</span> <span class="title">creator</span><span class="params">(param: <span class="type">P</span>)</span></span>: T</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">getInstance</span><span class="params">(param: <span class="type">P</span>)</span></span>: T =</span><br><span class="line">        instance ?: synchronized(<span class="keyword">this</span>) &#123;</span><br><span class="line">            <span class="comment">//            ④</span></span><br><span class="line">            <span class="comment">//            ↓</span></span><br><span class="line">            instance ?: creator(param).also &#123; instance = it &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​	在仔细分析每一处注释之前，我们先来整体看一下上面的代码：我们定义了一个抽象类 BaseSingleton，在这个抽象类当中，我们把单例当中通用的“INSTANCE 实例”和“getInstance() 函数”放了进去。也就是说，我们把单例类当中的核心逻辑放到了抽象类当中去了。</p>
<p>现在，我们再来看看上面的 4 处注释。</p>
<ul>
<li>注释①：abstract 关键字，代表了我们定义的 BaseSingleton 是一个抽象类。我们以后要实现单例类，就只需要继承这个 BaseSingleton 即可。</li>
<li>注释②：in P, out T 是 Kotlin 当中的泛型，P 和 T 分别代表了 getInstance() 的参数类型和返回值类型</li>
<li>注释③：creator(param: P): T 是 instance 构造器，它是一个抽象方法，需要我们在具体的单例子类当中实现此方法。</li>
<li>注释④：creator(param) 是对 instance 构造器的调用。</li>
</ul>
<p>这里，我们就以前面的 UserManager、PersonManager 为例，用抽象类模板的方式来实现单例，看看代码会发生什么样的变化。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">PersonManager</span> <span class="keyword">private</span> <span class="keyword">constructor</span>(name: String) &#123;</span><br><span class="line">    <span class="comment">//               ①                  ②</span></span><br><span class="line">    <span class="comment">//               ↓                   ↓</span></span><br><span class="line">    <span class="keyword">companion</span> <span class="keyword">object</span> : BaseSingleton&lt;String, PersonManager&gt;() &#123;</span><br><span class="line">    <span class="comment">//                  ③</span></span><br><span class="line">    <span class="comment">//                  ↓ </span></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">creator</span><span class="params">(param: <span class="type">String</span>)</span></span>: PersonManager = PersonManager(param)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">UserManager</span> <span class="keyword">private</span> <span class="keyword">constructor</span>(name: String) &#123;</span><br><span class="line">    <span class="keyword">companion</span> <span class="keyword">object</span> : BaseSingleton&lt;String, UserManager&gt;() &#123;</span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">creator</span><span class="params">(param: <span class="type">String</span>)</span></span>: UserManager = UserManager(param)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>下面我们来分析上面的 3 处注释。</p>
<ul>
<li>注释①：companion object : BaseSingleton，由于伴生对象本质上还是嵌套类，也就是说，它仍然是一个类，那么它就具备类的特性“继承其他的类”。因此，我们让伴生对象继承 BaseSingleton 这个抽象类。</li>
<li>注释②：String, PersonManager，这是我们传入泛型的参数 P、T 对应的实际类型，分别代表了 creator() 的“参数类型”和“返回值类型”。</li>
<li>注释③：override fun creator，我们在子类当中实现了 creator() 这个抽象方法。</li>
</ul>
<p>​	至此，我们就完成了单例的“抽象类模板”。通过这样的方式，我们不仅将重复的代码都统一封装到了抽象类“BaseSingleton”当中，还大大简化了单例的实现难度。</p>
<p>​	接下来，让我们对比着看看单例的“接口模板”。</p>
<h6 id="第四种：类抽象模板"><a href="#第四种：类抽象模板" class="headerlink" title="第四种：类抽象模板"></a>第四种：类抽象模板</h6><p>​	首先需要重点强调，<strong>这种方式是不被推荐的</strong>，这里提出这种写法是为了让你熟悉 Kotlin 接口的特性，并且明白 Kotlin 接口虽然能做到这件事，但它做得并不够好。</p>
<p>​	如果你理解了上面的“抽象类模板”，那么，接口的这种方式你应该也很容易就能想到：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">ISingleton</span>&lt;<span class="type">P, T</span>&gt; &#123;</span><br><span class="line">    <span class="comment">// ①</span></span><br><span class="line">    <span class="keyword">var</span> instance: T?</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">creator</span><span class="params">(param: <span class="type">P</span>)</span></span>: T</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">getInstance</span><span class="params">(p: <span class="type">P</span>)</span></span>: T =</span><br><span class="line">        instance ?: synchronized(<span class="keyword">this</span>) &#123;</span><br><span class="line">            instance ?: creator(p).also &#123; instance = it &#125;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​	可以看到，接口模板的代码结构和抽象类的方式如出一辙。而我们之所以可以这么做，也是因为 Kotlin 接口的两个特性：<strong>接口属性、接口方法默认实现</strong>。Kotlin 当中的接口被增强了，让它与抽象类越来越接近，这个例子正好就可以说明这一点。抽象类能实现单例模板，我们的接口也可以。</p>
<p>​	说实话，上面的接口单例模板看起来还是比较干净的，好像也挑不出什么大的毛病。但实际上，如果你看注释①的地方，你会发现：</p>
<ul>
<li><strong>instance 无法使用 private 修饰</strong>。这是接口特性规定的，而这并不符合单例的规范。正常情况下的单例模式，我们内部的 instance 必须是 private 的，这是为了防止它被外部直接修改。</li>
<li><strong>instance 无法使用 @Volatile 修饰</strong>。这也是受限于接口的特性，这会引发多线程同步的问题。</li>
</ul>
<p>除了 ISingleton 接口有这样的问题，我们在实现 ISingleton 接口的类当中，也会有类似的问题。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Singleton</span> <span class="keyword">private</span> <span class="keyword">constructor</span>(name: String) &#123;</span><br><span class="line">    <span class="keyword">companion</span> <span class="keyword">object</span>: ISingleton&lt;String, Singleton&gt; &#123;</span><br><span class="line">        <span class="comment">//  ①      ②</span></span><br><span class="line">        <span class="comment">//  ↓       ↓</span></span><br><span class="line">        <span class="meta">@Volatile</span> <span class="keyword">override</span> <span class="keyword">var</span> instance: Singleton? = <span class="literal">null</span></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">creator</span><span class="params">(param: <span class="type">String</span>)</span></span>: Singleton = Singleton(param)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>注释①：@Volatile，这个注解虽然可以在实现的时候添加，但实现方可能会忘记，这会导致隐患。</li>
<li>注释②：我们在实现 instance 的时候，仍然无法使用 private 来修饰。</li>
</ul>
<p>​	此综合来看，单例“接口模板”并不是一种合格的实现方式。</p>
<p>​	不过，在研究这个接口模板的过程中，我们又重温了 Kotlin 接口属性、接口方法默认实现这两个特性，并且对这两个特性进行一次应用。与此同时，我们也理解了接口模板存在的缺陷，以及不被推荐的原因。</p>
<h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><p>​	Kotlin 的匿名内部类和 Java 的类似，只不过它多了一个功能：匿名内部类可以在继承一个抽象类的同时还实现多个接口。</p>
<p>​	另外，object 的单例和伴生对象，这两种语义从表面上看是没有任何联系的。但通过这节课的学习我们发现了，<strong>单例与伴生对象之间是存在某种演变关系的。“单例”演变出了“嵌套单例”，而“嵌套单例”演变出了“伴生对象”。</strong></p>
<p>​	然后，我们也借助 Kotlin 伴生对象这个语法，研究了伴生对象的实战应用，比如可以实现工厂模式、懒加载 + 带参数的单例模式。</p>
<p>​	这 4 种单例之间各有优劣，我们可以在工作中根据实际需求，来选择对应的实现方式：</p>
<ul>
<li>如果我们的单例占用内存很小，并且对内存不敏感，不需要传参，直接使用 object 定义的单例即可。</li>
<li>如果我们的单例占用内存很小，不需要传参，但它内部的属性会触发消耗资源的网络请求和数据库查询，我们可以使用 object 搭配 by lazy 懒加载。</li>
<li>如果我们的工程很简单，只有一两个单例场景，同时我们有懒加载需求，并且 getInstance() 需要传参，我们可以直接手写 Double Check。</li>
<li>如果我们的工程规模大，对内存敏感，单例场景比较多，那我们就很有必要使用抽象类模板 BaseSingleton 了。</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://devsu.top">Carl Su</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://devsu.top/posts/c4e3d35a/">https://devsu.top/posts/c4e3d35a/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://devsu.top" target="_blank">码行</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Kotlin/">Kotlin</a></div><div class="post_share"><div class="social-share" data-image="https://img2.baidu.com/it/u=2005100522,649410059&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/606bc819/" title="Kotlin--扩展"><img class="cover" src="https://img0.baidu.com/it/u=358900677,557131950&amp;fm=253&amp;fmt=auto&amp;app=120&amp;f=JPEG?w=864&amp;h=486" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Kotlin--扩展</div></div></a></div><div class="next-post pull-right"><a href="/posts/3fd372c/" title="iOS 控件遮盖问题"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">iOS 控件遮盖问题</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/85d82fa8/" title="Kotlin编程第一课--(基础篇)06  扩展：你的能力边界到底在哪里？"><img class="cover" src="https://static001.geekbang.org/resource/image/b6/1c/b65feyy0bdc4764c6564a95912d7851c.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-06</div><div class="title">Kotlin编程第一课--(基础篇)06  扩展：你的能力边界到底在哪里？</div></div></a></div><div><a href="/posts/be9f17d6/" title="Kotlin编程第一课(目录)"><img class="cover" src="https://img2.baidu.com/it/u=3956021957,3313212296&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-10</div><div class="title">Kotlin编程第一课(目录)</div></div></a></div><div><a href="/posts/83a7144c/" title="2023-01-17-Kotlin协程 -  结构化并发"><img class="cover" src="https://s2.loli.net/2023/03/14/xEyFgn24zZPXe15.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-17</div><div class="title">2023-01-17-Kotlin协程 -  结构化并发</div></div></a></div><div><a href="/posts/68bf7d20/" title="Kotlin函数"><img class="cover" src="https://img1.baidu.com/it/u=1546227440,2897989905&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Kotlin函数</div></div></a></div><div><a href="/posts/a20c9e06/" title="Kotlin协程"><img class="cover" src="https://s2.loli.net/2023/03/14/3MHPBy1Q4GncRlF.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-09</div><div class="title">Kotlin协程</div></div></a></div><div><a href="/posts/8c331668/" title="Kotlin内置函数apply、let、run、with、also等区别"><img class="cover" src="https://s2.loli.net/2023/03/14/OpxWcuy2ktMzoQD.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Kotlin内置函数apply、let、run、with、also等区别</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div><div id="comment-switch"><span class="first-comment">Valine</span><span class="switch-btn"></span><span class="second-comment">Disqus</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div><div><div id="disqus_thread"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8C%BF%E5%90%8D%E5%86%85%E9%83%A8%E7%B1%BB"><span class="toc-number">1.</span> <span class="toc-text">匿名内部类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F"><span class="toc-number">2.</span> <span class="toc-text">单例模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#object-%E4%BC%B4%E7%94%9F%E5%AF%B9%E8%B1%A1"><span class="toc-number">3.</span> <span class="toc-text">object: 伴生对象</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BC%B4%E7%94%9F%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%AE%9E%E6%88%98%E5%BA%94%E7%94%A8"><span class="toc-number">3.1.</span> <span class="toc-text">伴生对象的实战应用</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F"><span class="toc-number">3.1.1.</span> <span class="toc-text">工厂模式</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%8F%A6%E5%A4%964%E4%B8%AD%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%E7%9A%84%E5%86%99%E6%B3%95"><span class="toc-number">3.1.2.</span> <span class="toc-text">另外4中单例模式的写法</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#%E7%AC%AC%E4%B8%80%E7%A7%8D%EF%BC%9A%E6%87%92%E5%8A%A0%E8%BD%BD%E5%A7%94%E6%89%98"><span class="toc-number">3.1.2.1.</span> <span class="toc-text">第一种：懒加载委托</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E7%AC%AC%E4%BA%8C%E7%A7%8D-%E4%BC%B4%E7%94%9F%E5%AF%B9%E8%B1%A1Double-Check"><span class="toc-number">3.1.2.2.</span> <span class="toc-text">第二种: 伴生对象Double Check</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E7%AC%AC%E4%B8%89%E7%A7%8D%EF%BC%9A-%E7%B1%BB%E6%8A%BD%E8%B1%A1%E6%A8%A1%E6%9D%BF"><span class="toc-number">3.1.2.3.</span> <span class="toc-text">第三种： 类抽象模板</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E7%AC%AC%E5%9B%9B%E7%A7%8D%EF%BC%9A%E7%B1%BB%E6%8A%BD%E8%B1%A1%E6%A8%A1%E6%9D%BF"><span class="toc-number">3.1.2.4.</span> <span class="toc-text">第四种：类抽象模板</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-number">4.</span> <span class="toc-text">小结</span></a></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2018 - 2023 By Carl Su</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">学无止境</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '',
      appKey: '',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script>function loadDisqus () {
  var disqus_config = function () {
    this.page.url = 'https://devsu.top/posts/c4e3d35a/'
    this.page.identifier = '/posts/c4e3d35a/'
    this.page.title = 'Kotlin -- Object关键字'
  };

  window.disqusReset = () => {
    DISQUS.reset({
      reload: true,
      config: disqus_config
    })
  }

  if (window.DISQUS) disqusReset()
  else {
    (function() { 
      var d = document, s = d.createElement('script');
      s.src = 'https://.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
    })();
  }

  document.getElementById('darkmode').addEventListener('click', () => {
    setTimeout(() => window.disqusReset(), 200)
  })
}

if ('Valine' === 'Disqus' || !true) {
  if (true) btf.loadComment(document.getElementById('disqus_thread'), loadDisqus)
  else loadDisqus()
} else {
  function loadOtherComment () {
    loadDisqus()
  }
}
</script></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>